import requests
import smtplib
from email.mime.text import MIMEText
from email.header import Header
from config_loader import load_config
from service.club_handler import get_sign_in_alarms_club
from service.handler import mysql_db, PREFIX_STR, weekday_dict, send_to_server_chan
from datetime import datetime, timedelta, time, date

# 加载配置
cfg = load_config("config.yml")
PUSH_PLUS_TOKEN = cfg["PUSH_PLUS_TOKEN"]


def send_text_msg_push_plus(token, content, alarms_str_length, purchase_alarm_time):
    title = f"【{purchase_alarm_time}】有{alarms_str_length}个抢购任务"
    url = 'http://www.pushplus.plus/send'
    data = {
        "token": token,
        "title": title,
        "content": content
    }
    result = requests.post(url, data=data)
    return result


def send_msg_email(content, alarms_str_length, purchase_alarm_time):
    title = f"【{purchase_alarm_time}】有{alarms_str_length}个抢购任务"
    # 发送邮件服务器地址
    smtp_server = 'smtp.163.com'
    # 发送方账号
    sender = 'tianshunguang@163.com'
    # 发送方授权密码
    password = 'ULWDWJOZOKYDJQQU'
    # 收件方邮箱
    receiver = '1204371912@qq.com'
    # 邮件标题
    subject = title
    # 邮件内容
    mail_msg = content
    # 三个参数：第一个为文本内容，第二个 plain 设置文本格式，html 设置文本格式为html格式  第三个 utf-8 设置编码
    message = MIMEText(mail_msg, 'plain', 'utf-8')  # 发送内容 （文本内容，发送格式，编码格式）
    # 发送地址
    message['From'] = sender
    # 接受地址
    message['To'] = receiver
    # 邮件标题
    message['Subject'] = Header(subject, 'utf-8')
    try:
        print("发送邮件")
        # 创建SMTP对象
        smtp = smtplib.SMTP_SSL(smtp_server)
        # smtp.set_debuglevel(1)
        # 登录邮箱账号
        smtp.login(sender, password)
        # 发送账号信息
        smtp.sendmail(sender, receiver, message.as_string())
        print('success:发送成功')
    except smtplib.SMTPException:
        print('error:邮件发送失败')
    finally:
        # 关闭
        smtp.quit()


def task_alarms_purchase_push_plus():
    # 获取当前时间和星期、月份信息
    now = datetime.now()
    weekday = '每周' + weekday_dict[now.strftime('%A')]
    date = '每月' + now.strftime('%d') + '号'
    # 从数据库中获取所有闹钟,获取接下来5分钟内需要推送消息的闹钟事件
    conn = mysql_db()
    alarms = get_sign_in_alarms_club(conn, '抢购')
    print('alarms=', alarms)
    for alarm in alarms:
        # 将闹钟的时间（当天的秒数）转换为具体的时间
        alarm_time = datetime.combine(now.date(), time(0)) + timedelta(seconds=int(alarm[3]))
        # 检查当前时间是否在闹钟时间前的5分钟，并且当前日期在闹钟的开始日期和结束日期之间
        start_date_obj = datetime.strptime(alarm[1], '%m月%d日').date().replace(year=2023)
        end_date_obj = datetime.strptime(alarm[2], '%m月%d日').date().replace(year=2023)

        alarmed_time = datetime.strptime(alarm[9], '%Y-%m-%d %H:%M:%S') if alarm[9] else None
        if alarm[3] == '0':
            alarm_date = now.date() + timedelta(days=1)
        else:
            alarm_date = now.date()
        if 0 <= (alarm_time - now).total_seconds() <= 300 and start_date_obj <= alarm_date <= end_date_obj:
            frequency = alarm[4]
            if frequency == '每天' or frequency == weekday or frequency == date:
                # 如果在5分钟内，但是alarm_time字段日期为今日，说明今天已经推送过，不再推送，执行下一个alarm
                if not alarmed_time or alarmed_time.date() != now.date():
                    print("Sending reminder for alarm:", alarm[4])
                    # 发送提示消息
                    send_text_msg_push_plus(PUSH_PLUS_TOKEN, '闹钟提醒', alarm[4])
                    # 更新alarmed_time为当前的时间
                    cur = conn.cursor()
                    cur.execute("UPDATE alarms SET alarmed_time = %s WHERE id = %s",
                                (now.strftime('%Y-%m-%d %H:%M:%S'), alarm[0]))
                    conn.commit()
        else:
            print('此次定时任务没有需要推送消息的事件')


############################################ 每日抢购任务消息推送【push_plus推送】 ############################################
def task_alarms_purchase_push_plus_v2():
    alarms_str, alarms_str_length, purchase_alarm_time = get_today_alarms_purchase_v3()
    responses = ''.join(alarms_str)
    if len(alarms_str) > 0:
        send_text_msg_push_plus(PUSH_PLUS_TOKEN, responses, alarms_str_length, purchase_alarm_time)
    else:
        print('现在没有抢购任务要做，在等等吧......')


def get_today_alarms_purchase_v2():
    # 获取今天的日期和星期
    today = datetime.now()
    weekday = '每周' + weekday_dict[today.strftime('%A')]
    date_str = '每月' + today.strftime('%d') + '号'
    # 获取当前时间
    now = datetime.now()
    # 从数据库中获取所有打卡类型的事件,获取接下来5分钟内需要推送消息的闹钟事件
    conn = mysql_db()
    alarms = get_sign_in_alarms_club(conn, '抢购')
    # 否则，收集所有的闹钟事件
    alarms_str = []
    # 在开头添加一个大标题
    alarms_str.append('春风若有怜花意，可否许我再少年  \n' + PREFIX_STR + '  \n')
    for alarm in alarms:
        # 检查当前时间是否在闹钟时间前的5分钟，并且当前日期在闹钟的开始日期和结束日期之间
        start_date_obj = datetime.strptime(alarm[1], '%Y-%m-%d').date()
        end_date_obj = datetime.strptime(alarm[2], '%Y-%m-%d').date()
        if start_date_obj <= now.date() <= end_date_obj:
            if alarm[4] == '每天' or alarm[4] == weekday or alarm[4] == date_str:
                if alarm[9] == 0:
                    alarm_time = datetime.strptime(alarm[3], '%H:%M').time()
                    # 计算当前时间和 alarm_time 的差值
                    time_diff = datetime.combine(date.today(), alarm_time) - datetime.combine(date.today(), now.time())
                    # 如果当前时间距离 alarm_time 还有 5 分钟
                    if timedelta(minutes=5) <= time_diff < timedelta(minutes=6):
                        if alarm[12] == 0 and alarm[13] == 0:
                            # 将每个闹钟的信息分别添加到列表中
                            alarm_info = f"【{alarm[8]}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + PREFIX_STR + '  \n'
                            alarms_str.append(alarm_info)
                        elif alarm[12] == 0 and alarm[13] > 0:
                            if alarm[11] < alarm[13]:
                                # 将每个闹钟的信息分别添加到列表中
                                alarm_info = f"【{alarm[8]}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + PREFIX_STR + '  \n'
                                alarms_str.append(alarm_info)
                        elif alarm[12] > 0 and alarm[13] > 0:
                            if alarm[10] < alarm[12] and alarm[11] < alarm[13]:
                                # 将每个闹钟的信息分别添加到列表中
                                alarm_info = f"【{alarm[8]}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + PREFIX_STR + '  \n'
                                alarms_str.append(alarm_info)

    return alarms_str


alarms_prefix = '------------------------------------------------'


def get_today_alarms_purchase_v3():
    # 获取今天的日期和星期
    today = datetime.now()
    weekday = '每周' + weekday_dict[today.strftime('%A')]
    date_str = '每月' + today.strftime('%d') + '号'
    tom_weekday = '每周' + weekday_dict[(today + timedelta(days=1)).strftime('%A')]  # 获取明天的星期
    tom_date_str = '每月' + (today + timedelta(days=1)).strftime('%d') + '号'  # 获取明天的日期
    # 获取当前时间
    now = datetime.now()
    # 从数据库中获取所有打卡类型的事件,获取接下来5分钟内需要推送消息的闹钟事件
    conn = mysql_db()
    alarms = get_sign_in_alarms_club(conn, '抢购')
    # 否则，收集所有的闹钟事件
    alarms_str = []
    purchase_alarm_time = ""
    for i, alarm in enumerate(alarms, start=1):
        # 检查当前时间是否在闹钟时间前的5分钟，并且当前日期在闹钟的开始日期和结束日期之间
        start_date_obj = datetime.strptime(alarm[1], '%Y-%m-%d').date()
        end_date_obj = datetime.strptime(alarm[2], '%Y-%m-%d').date()
        if start_date_obj <= now.date() <= end_date_obj:
            # 如果抢购时间是今天，不涉及跨天情况
            if (alarm[4] == '每天' and alarm[3] != '00:00') or alarm[4] == weekday or alarm[4] == date_str:
                if alarm[9] == 0:
                    alarm_time = datetime.strptime(alarm[3], '%H:%M').time()
                    # 计算当前时间和 alarm_time 的差值
                    time_diff = datetime.combine(date.today(), alarm_time) - datetime.combine(date.today(), now.time())
                    # 如果当前时间距离 alarm_time 还有 5 分钟
                    if 5 <= time_diff.total_seconds() // 60 < 6:
                        purchase_alarm_time = alarm_time.strftime('%H:%M')
                        if alarm[12] == 0 and alarm[13] == 0:
                            # 将每个闹钟的信息分别添加到列表中
                            alarm_info = f"【{alarm[8]}{i}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + alarms_prefix + '  \n'
                            alarms_str.append(alarm_info)
                        elif alarm[12] == 0 and alarm[13] > 0:
                            if alarm[11] < alarm[13]:
                                # 将每个闹钟的信息分别添加到列表中
                                alarm_info = f"【{alarm[8]}{i}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + alarms_prefix + '  \n'
                                alarms_str.append(alarm_info)
                        elif alarm[12] > 0 and alarm[13] > 0:
                            if alarm[10] < alarm[12] and alarm[11] < alarm[13]:
                                # 将每个闹钟的信息分别添加到列表中
                                alarm_info = f"【{alarm[8]}{i}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + alarms_prefix + '  \n'
                                alarms_str.append(alarm_info)
            # 如果抢购时间是明天，涉及跨天情况
            elif (alarm[4] == '每天' and alarm[3] == '00:00') or alarm[4] == tom_weekday or alarm[4] == tom_date_str:
                if alarm[9] == 0:
                    alarm_time = datetime.strptime(alarm[3], '%H:%M').time()
                    # 计算当前时间和 alarm_time 的差值
                    time_diff = datetime.combine(date.today() + timedelta(days=1), alarm_time) - datetime.combine(
                        date.today(), now.time())
                    # 如果当前时间距离 alarm_time 还有 5 分钟
                    print(time_diff.total_seconds() // 60)
                    if 5 <= time_diff.total_seconds() // 60 < 6:
                        purchase_alarm_time = alarm_time.strftime('%H:%M')
                        if alarm[12] == 0 and alarm[13] == 0:
                            # 将每个闹钟的信息分别添加到列表中
                            alarm_info = f"【{alarm[8]}{i}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + alarms_prefix + '  \n'
                            alarms_str.append(alarm_info)
                        elif alarm[12] == 0 and alarm[13] > 0:
                            if alarm[11] < alarm[13]:
                                # 将每个闹钟的信息分别添加到列表中
                                alarm_info = f"【{alarm[8]}{i}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + alarms_prefix + '  \n'
                                alarms_str.append(alarm_info)
                        elif alarm[12] > 0 and alarm[13] > 0:
                            if alarm[10] < alarm[12] and alarm[11] < alarm[13]:
                                # 将每个闹钟的信息分别添加到列表中
                                alarm_info = f"【{alarm[8]}{i}】{alarm[5]}  \n" + f"【内容】{alarm[6]}  \n" + f"【直达】{alarm[7]}  \n" + alarms_prefix + '  \n'
                                alarms_str.append(alarm_info)
    # 获取 alarms_str 的长度
    alarms_str_length = len(alarms_str)
    return alarms_str, alarms_str_length, purchase_alarm_time


############################################ 每日抢购任务消息推送【QQ邮箱推送】 ############################################
def task_alarms_purchase_QQ_Email():
    alarms_str, alarms_str_length, purchase_alarm_time = get_today_alarms_purchase_v3()
    responses = ''.join(alarms_str)
    if len(alarms_str) > 0:
        send_msg_email(responses, alarms_str_length, purchase_alarm_time)
    else:
        print('当前时间没有抢购任务......')
